package com.bfxy.disruptor.common.waitStraty;

import com.bfxy.disruptor.common.balance.Sequence;
import com.bfxy.disruptor.common.balance.SequenceBarrier;
import com.bfxy.disruptor.common.exception.AlertException;

//无锁的方式。无锁方式signalAllWhenBlocking是空实现，等待的时候applyWaitMethod。性能是最高的。
public final class YieldingWaitStrategy implements WaitStrategy {
	private static final int SPIN_TRIES = 100;

	@Override
	public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence,
			final SequenceBarrier barrier) throws AlertException, InterruptedException {
		long availableSequence;
		int counter = SPIN_TRIES;// 每次调用这个方法，counter是100，
		while ((availableSequence = dependentSequence.get()) < sequence) {
			counter = applyWaitMethod(barrier, counter);// 空循环
		}
		return availableSequence;
	}

	@Override
	public void signalAllWhenBlocking() {
	}

	private int applyWaitMethod(final SequenceBarrier barrier, int counter) throws AlertException {
		barrier.checkAlert();

		if (0 == counter) {
			Thread.yield();// 减到0就一直yield，避免一个线程长时间占有 CPU 资源。
		} else {
			--counter;
		}

		return counter;
	}
}
